<?php
/*
Plugin Name: Property Manager
Version: 0.5.1-Beta
Plugin URI: http://code.google.com/p/propmanager
Description: This plugin allows the simple listing and de-listing of available sale and rental properties
Author: Kyle Klaus
Author URI: http://indemnity83.com
*/

define(PROPMANAGER_PLUGIN_FILE, dirname(__FILE__) . '/propmanager.php');
define(PROPMANAGER_VERSION, 0.5);

add_action('admin_menu', 'propmanager_menu');
add_action('admin_head', 'propmanager_admin_css');
add_action('wp_head', 'propmanager_list_css');
add_filter('the_content','propmanager_init');

function propmanager_menu() {
	$basename = basename(PROPMANAGER_PLUGIN_FILE);
        
	add_menu_page('Property Manager', 'Properties', 'edit_posts', $basename, 'propmanager_actions');
	add_submenu_page($basename, __('Edit'), __('Edit'), 'edit_posts', $basename, 'propmanager_actions');
	add_submenu_page($basename, __('Add New'), __('Add New'), 'edit_posts', 'prop-add.php', 'propmanager_actions');
}

function propmanager_actions() {
	global $wpdb;

	switch ($_GET['page']) {
		case 'prop-add.php':
			switch($_GET['op']) {
				case 'submit':
					if( $_POST['title'] == '' ) {
						$error = 'A title is required';
					} else {
						$sql = 'INSERT INTO `'.$wpdb->prefix.'properties` (
									`prop_id`, 
									`name`, 
									`address1`, 
									`address2`, 
									`price`, 
									`bed`, 
									`bath`, 
									`tagline`, 
									`features`, 
									`description`, 
									`information`, 
									`image`, 
									`status`
								) VALUES (
									\'\', 
									\''.$_POST['title'].'\', 
									\''.$_POST['address1'].'\', 
									\''.$_POST['address2'].'\', 
									\''.$_POST['price'].'\', 
									\''.$_POST['beds'].'\', 
									\''.$_POST['bath'].'\', 
									\''.$_POST['excerpt'].'\', 
									\''.$_POST['features'].'\', 
									\''.$_POST['description'].'\', 
									\''.$_POST['info'].'\', 
									\'\', 
									\'unavailable\'
								)';
						$result = $wpdb->query($sql);
						if ($result === false) {
							$error = $wpdb->error->get_error_message();
						} else {
							$msg = 'The property was added, you can now add another.';
						}
					}
				default:
					print '<div class="wrap">'; 
					if( $error != '') { print '<div class="error"><p>'.$error.'</p></div>'; }
					print '<div id="icon-property" class="icon32"><br /></div>';
					print '<h2>'.__('Add New Property', 'propmanager').'</h2>' ;			
					if( $msg != '') { print '<div id="message" class="updated fade"><p>'.$msg.'</p></div>'; }
					print '<form name="post" action="admin.php?page=prop-add.php&op=submit" method="post" id="post">';
					require(dirname(__FILE__) . '/forms/edit.php');		
					print '</form>';
					print '</div>';
					break;
				}
			break;
		case 'prop-edit.php':
			print '<div class="wrap">'; 
			print '<div id="icon-property" class="icon32"><br /></div>';
			print '<h2>'.__('Edit Property', 'propmanager').'</h2>' ;	
			print '<form name="post" action="?page=prop-edit.php&op=submit" method="post" id="post">';			
			require(dirname(__FILE__) . '/forms/edit.php');			
			print '</form>';
			print '</div>';
			break;
		default:	
			switch( $_POST['op'] ) {
				case available:
				case unavailable:
				case featured:
					$id = implode(',',$_POST['id']);
					$query = 'UPDATE `'.$wpdb->prefix.'properties` SET status = \''.$_POST['op'].'\' WHERE prop_id IN ('.$id.');';
					$result = $wpdb->query($query);
					if ($result === false) {
						$error = $wpdb->error->get_error_message();
					} else {
						$msg = 'The properties were updated';
					}
					break;
				case 'delete':
					$id = implode(',',$_POST['id']);
					$query = 'DELETE FROM `'.$wpdb->prefix.'properties` WHERE prop_id IN ('.$id.');';
					$result = $wpdb->query($query);
					if ($result === false) {
						$error = $wpdb->error->get_error_message();
					} else {
						$msg = 'The properties were deleted';
					}
					break;
			}
			
			print '<div class="wrap">'; 
			if( $error != '') { print '<div class="error"><p>'.$error.'</p></div>'; }
			print '<div id="icon-property" class="icon32"><br /></div>';
			print '<h2>'.__('Edit Properties', 'propmanager').'</h2>' ;
			if( $msg != '') { print '<div id="message" class="updated fade"><p>'.$msg.'</p></div>'; }
			print '<form name="post" action="admin.php?page=propmanager.php" method="post" id="post">';		
			require(dirname(__FILE__) . '/forms/list.php');						
			print '</form>';
			print '</div>';
			break;
			
	}
}

/**
 * Generate the listing code
 */
function propmanager_list() {
	global $wpdb;
	$results = $wpdb->get_results("SELECT * FROM `".$wpdb->prefix."properties` WHERE status IN ('available','featured') ORDER BY status DESC");
	foreach ($results as $result) {
		print '<div class="rowDefault sResultsRow">';
		print '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
		print '<td valign="top" class="sResultsImgPreview"><a href="/contact"><img src="/wp-content/plugins/propmanager/noimage.jpg" width=122 height=92 alt="'.$result->name.'" border=0></a></td>';
		print '<td valign="top">';
		print '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
		print '<tr>';
		print '<td width="113" valign="top" nowrap="nowrap"><div class="sResultsPriceRange">'.$result->price.'</div><div class="sResultsPropDetails">Bed: '.$result->bed.'<br />Bath: '.$result->bath.'</div><div class="padTop2"><img border="0" src="/wp-content/plugins/propmanager/'.( $result->status == 'featured' ? 'featured.gif' : 'blank.gif' ).'" width="105" height="13" alt="'.( $result->status == 'featured' ? 'Featured' : '' ).'" /></div></td>';
		print '<td width="100%" valign="top" class="padLeft10"><div class="sResultsPropAddress">';
		print '<a href="/contact" class="sResultsPropName">'.$result->name.'</a><br />'.$result->address2.'';
		print '</div><div class="FONTRegular"></div></td>';
		print '<td valign="top" align="right" nowrap="nowrap" class="alignCenter"><div class="padBot5">&nbsp;</div>';
		print '</td>';
		print '</tr>';
		print '<tr>';
		print '<td colspan="3">';
		print '</td>';
		print '</tr>';
		print '<tr><td colspan="3" class="sResultsQuote">'.$result->tagline.'</td></tr>';
		print '</table>';
		print '</td></tr></table>';
		print '</div>';
	}
}

/**
 * Define CSS for Admin pages
 */
function propmanager_admin_css() {	
	print '<style type="text/css">';
	print '#icon-property {';
	print '    background: transparent url(../wp-content/plugins/propmanager/icon.png) no-repeat -5px;';
	print '}';
	print '</style>';
}

/**
 * Define CSS for listing
 */
function propmanager_list_css() {	
	print '<style type="text/css">';
	print '    .sResultsRow{padding-top:8px; padding-bottom:8px; border-bottom:1px solid #d9d9d9; cursor:hand; cursor:pointer;}';
	print '    .sResultsRow2{padding-top:8px; padding-bottom:8px; border-bottom:1px solid #d9d9d9;}';
	print '    .sResultsImgPreview{padding-left:2px; padding-right:10px; width:125px;}';
	print '    .sResultsPriceRange{font-size:15px; font-weight:bold; color:#008000; line-height:16px;}';
	print '    .sResultsPropDetails{font-size:13px; color:#333333; line-height:16px;}';
	print '    .sResultsPropAddress{color:#333333; line-height:16px; font-size:12px;}';
	print '    .sResultsPropName, a:link.sResultsPropName, a:visited.sResultsPropName, a:hover.sResultsPropName, a:active.sResultsPropName{text-decoration:none; font-weight:bold; color:#333333;}';
	print '    .sResultsQuote{line-height:16px; font-size:12px;}';
	print '    .rewardsListBox{padding-top: 3px;z-index:2020;}';
	print '    .rewardsListBox p {margin:0;color: #008000; font-size:10px; font-weight:bold;}';
	print '    .rewardsListBox img {vertical-align:middle;margin-right:5px;}';
	print '</style>';
}


/**
 * Replace tag in content with listings
 */
function propmanager_init($content){
	if( strpos($content, '[PROPMANAGER]') === false ){
		return $content;
	} else {
		$code = propmanager_list();
		$content = str_replace( '[PROPMANAGER]', $code, $content );
		return $content;
	}
}

/**
 * Adds/updates the options on plug-in activation.
 */
function propmanager_install($allow_database_install=true)
{
    propmanager_install_database($version);
    update_option('propmanager__version', PROPMANAGER_VERSION);
}

/**
 * Initializes the database if it's not already present.
 */
function propmanager_install_database($version) {
	global $wpdb;
	$sql = 'CREATE TABLE IF NOT EXISTS `'.$wpdb->prefix.'properties` (
			`prop_id` bigint(20) NOT NULL auto_increment,
			`name` varchar(200) NOT NULL,
			`address1` varchar(200) NULL,
			`address2` varchar(200) NULL,
			`price` varchar(200) NULL,
			`bed` int(2) NULL,
			`bath` int(2) NULL,
			`tagline` varchar(200) NULL,
			`features` text NULL,
			`description` text NULL,
			`information` text NULL,
			`image` varchar(200) NULL,
			`status` enum(\'available\',\'unavailable\',\'featured\') NOT NULL,
			PRIMARY KEY  (`prop_id`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8;';
	$result = $wpdb->query($sql);
}

?>
